#pragma once
#include <xpam/com/com.h>

namespace DexterLib
{
    namespace dshow
    {
        HRESULT pin(IBaseFilterPtr & iFilter, _PinDirection pinDir, IPinPtr & iPin)
        {
            HRESULT_ex hr;
            IEnumPinsPtr iEnum;
            hr = iFilter->EnumPins(&iEnum);
            while(iEnum->Next(1, &iPin, 0) == S_OK)
            {
                _PinDirection pinDirThis;
                hr = iPin->QueryDirection(&pinDirThis);
                if (pinDir == pinDirThis)
                {
                    return S_OK;
                }
            }
            return E_FAIL;  
        }

        HRESULT input_pin(IBaseFilterPtr & iFilter, IPinPtr & iPin)
        {
            return pin(iFilter, PINDIR_INPUT, iPin);
        }

        IPinPtr input_pin(IBaseFilterPtr & filter)
        {
            IPinPtr pin1;
            pin(filter, PINDIR_INPUT, pin1);
            return pin1;
        }

        HRESULT output_pin(IBaseFilterPtr & iFilter, IPinPtr & iPin)
        {
            return pin(iFilter, PINDIR_OUTPUT, iPin);
        }

        IPinPtr output_pin(IBaseFilterPtr & filter)
        {
            IPinPtr pin1;
            pin(filter, PINDIR_OUTPUT, pin1);
            return pin1;
        }

        void MediaType_free(_AMMediaType& mt)
        {
            if (mt.cbFormat != 0)
            {
                ::CoTaskMemFree((PVOID)mt.pbFormat);
                mt.cbFormat = 0;
                mt.pbFormat = NULL;
            }
            if (mt.pUnk != NULL)
            {
                // Unnecessary because pUnk should not be used, but safest.
                mt.pUnk->Release();
                mt.pUnk = NULL;
            }
        }

    }
}